package com.dy.yunying.biz.controller.currency;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.yunying.api.dto.currency.UserCurrencyRecordDto;
import com.dy.yunying.api.req.currency.UserCurrencyRecordReq;
import com.dy.yunying.api.vo.UserCurrencyRecordVO;
import com.dy.yunying.biz.service.currency.UserCurrencyRecordService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.ExportUtils;
import com.pig4cloud.pig.common.core.fastjson.BigDecimalValueFilter;
import com.pig4cloud.pig.common.core.util.DateUtil;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 用户游豆明细
 *
 * @author hejiale
 * @date 2022-3-23 14:25:29
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/currencyRecord")
@Api(value = "currencyRecord", tags = "用户游豆明细")
@Slf4j
public class UserCurrencyRecordController {

	private final UserCurrencyRecordService userCurrencyRecordService;

	@SysLog("用户游豆明细列表")
	@PostMapping("/page")
	@PreAuthorize("@pms.hasPermission('CURRENCY_RECORD_PAGE')")
	public R<IPage<UserCurrencyRecordVO>> page(@Valid @RequestBody UserCurrencyRecordReq req){
		try {
			// 默认排序
			if (CollectionUtils.isEmpty(req.getOrders())) {
				List<OrderItem> orders = Arrays.asList(new OrderItem("t.create_time", false));
				req.setOrders(orders);
			}
			setDefaultTime(req);
			return userCurrencyRecordService.pageDto(req);
		} catch (Exception e) {
			log.error("用户游豆-列表:{}",e);
			return R.failed("用户游豆列表查询失败");
		}
	}

	/**
	 * 用户游豆明细导出
	 * @param req
	 * @return
	 */
	@SysLog("用户游豆明细导出")
	@ResponseExcel(name="用户游豆明细导出",sheet = "用户游豆明细导出")
	@RequestMapping("/export")
	@PreAuthorize("@pms.hasPermission('CURRENCY_RECORD_EXPORT')")
	public void export(@Valid @RequestBody UserCurrencyRecordReq req, HttpServletResponse response, HttpServletRequest request) {
		String sheetName = "用户游豆明细";
		try {
			// 默认排序
			if (CollectionUtils.isEmpty(req.getOrders())) {
				List<OrderItem> orders = Arrays.asList(new OrderItem("t.create_time", false));
				req.setOrders(orders);
			}
			setDefaultTime(req);
			List<UserCurrencyRecordDto> list = userCurrencyRecordService.exportRecord(req);
			// list对象转jsonArray
			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list,new BigDecimalValueFilter()));


//			// 为百分比的值拼接百分号
//			final String defaultValue = "0.00%";
//			ExportUtils.spliceSuffix(resultListMap, Constant.PERCENT, defaultValue, "roiratio", "sharing");
			// 导出
			ExportUtils.exportExcelData(request,response,"游豆明细-" + DateUtils.getCurrentTimeNoUnderline() + ".xlsx", sheetName,req.getTitles(),req.getColumns(), jsonArray);

		} catch (Exception e) {
			log.error("用户游豆明细导出失败,", e);
		}
	}

	/**
	 * 设置默认的开始结束时间
	 * @param req
	 */
	private void setDefaultTime(UserCurrencyRecordReq req) {
		// 时间标识，默认正确
		boolean timeFlag = true;
		Date startTime = req.getStartTime();
		Date endTime = req.getEndTime();
		if (null == startTime) {
			timeFlag = false;
			log.warn("开始时间不合法");
		}
		if (timeFlag && null == endTime) {
			timeFlag = false;
			log.warn("结束时间不合法");
		}
		if (timeFlag && endTime.getTime() <= startTime.getTime()) {
			timeFlag = false;
			log.warn("结束时间不能比开始时间小, startTime:{}, endTime:{}", startTime, endTime);
		}
		if (!timeFlag) {
			Date now = new Date();
			// 6天前
			startTime = DateUtils.stringToStartDate(DateUtils.dateToString(DateUtil.getDate(now, -6), DateUtils.YYYY_MM_DD), DateUtils.YYYY_MM_DD_HH_MM_SS);
			// 今天
			endTime = DateUtils.stringToEndDate(DateUtils.dateToString(now, DateUtils.YYYY_MM_DD), DateUtils.YYYY_MM_DD_HH_MM_SS);
			req.setStartTime(startTime);
			req.setEndTime(endTime);
		}
	}

}
